﻿using System.IO;
using System.Linq;
using Microsoft.Reporting.WebForms;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Web.Mvc;
using TamoCRM.Core;
using TamoCRM.Core.Commons.Utilities;
using TamoCRM.Core.Data;
using TamoCRM.Domain.Channels;
using TamoCRM.Domain.ConsultantNomrs;
using TamoCRM.Domain.ContactLevelInfos;
using TamoCRM.Domain.Contacts;
using TamoCRM.Domain.Levels;
using TamoCRM.Domain.Majors;
using TamoCRM.Domain.Phones;
using TamoCRM.Domain.StatusCare;
using TamoCRM.Domain.StatusMap;
using TamoCRM.Services.Channels;
using TamoCRM.Services.Collectors;
using TamoCRM.Services.ConsultantNomrs;
using TamoCRM.Services.ContactLevelInfos;
using TamoCRM.Services.Contacts;
using TamoCRM.Services.ImportExcels;
using TamoCRM.Services.Levels;
using TamoCRM.Services.Majors;
using TamoCRM.Services.Phones;
using TamoCRM.Services.PrintForCollaboratorContacts;
using TamoCRM.Services.PrintForCollaboratorPages;
using TamoCRM.Services.Status;
using TamoCRM.Services.StatusCare;
using TamoCRM.Services.StatusMap;
using TamoCRM.Services.UserRole;
using TamoCRM.Web.Framework;
using TamoCRM.Web.Framework.ActionFilters;
using TamoCRM.Web.Framework.Controllers;
using TamoCRM.Web.Framework.Users;
using TamoCRM.Web.Mvc.Areas.Admin.Models.ContactFilter;
using TamoCRM.Web.Mvc.Areas.Admin.Models.Contacts;
using TamoCRM.Core.Commons.Extensions;

namespace TamoCRM.Web.Mvc.Areas.Admin.Controllers
{
    public class ContactFilterController : AdminController
    {
        public ActionResult CCL1OfFilter()
        {
            return View();
        }
        public ActionResult CCL2OfFilter()
        {
            return View();
        }
        public ActionResult MOOfFilter()
        {
            return View();
        }
        public ActionResult HOTOfFilter()
        {
            return View();
        }

        public ActionResult PrintForCollaborators()
        {
            var channels = StoreData.ListChannel.Count > 0
                               ? StoreData.ListChannel
                               : ChannelRepository.GetAll();
            var lstChannelWithCount = new List<ChannelWithContactCountModel>();
            foreach (var channel in channels)
            {
                var obj = ObjectHelper.Transform<ChannelWithContactCountModel, ChannelInfo>(channel);
                lstChannelWithCount.Add(obj);
            }
            ViewBag.Channels = lstChannelWithCount;
            return View();
        }
        [NotAuthorizeAttribute]
        public ActionResult DoPrintForCollaborators(int printId, string pageCode)
        {

            var localReport = new LocalReport { ReportPath = Server.MapPath("~/Areas/Admin/Reports/rptPrintForCollaborators.rdlc") };
            var lstContactForPrints = PrintForCollaboratorContactRepository.GetForPrint(printId, pageCode);
            var reportDataSource = new ReportDataSource("PrintForCollaborators", lstContactForPrints);
            localReport.DataSources.Add(reportDataSource);
            localReport.SetParameters(new ReportParameter("PageCodePrefix", "XXXXXXXXX"));
            const string reportType = "pdf";
            string mimeType;
            string encoding;
            string fileNameExtension;
            //The DeviceInfo settings should be changed based on the reportType             
            //http://msdn2.microsoft.com/en-us/library/ms155397.aspx             
            const string deviceInfo = "<DeviceInfo>" +
                                      "  <OutputFormat>PDF</OutputFormat>" +
                                      "  <PageWidth>8.5in</PageWidth>" +
                                      "  <PageHeight>11in</PageHeight>" +
                                      "  <MarginTop>0.1in</MarginTop>" +
                                      "  <MarginLeft>0.1in</MarginLeft>" +
                                      "  <MarginRight>0.1in</MarginRight>" +
                                      "  <MarginBottom>0.1in</MarginBottom>" +
                                      "</DeviceInfo>";
            Warning[] warnings;
            string[] streams;
            //Render the report             
            var renderedBytes = localReport.Render(
                reportType,
                deviceInfo,
                out mimeType,
                out encoding,
                out fileNameExtension,
                out streams,
                out warnings);
            //Response.AddHeader("content-disposition", "attachment; filename=NorthWindCustomers." + fileNameExtension);             
            //Session["PrintId"] = null;
            return File(renderedBytes, mimeType);
        }
        [HttpPost]
        [NotAuthorizeAttribute]
        public string PrintForCollaborators(PrintForCollaboratorsModel model, FormCollection forms)
        {
            // Param
            var channels = StoreData.ListChannel.Count > 0 ? StoreData.ListChannel : ChannelRepository.GetAll();
            var maxRowPerPage = model.MaxRowsPerPage;
            var branchId = UserContext.GetDefaultBranch();
            var userId = UserContext.GetCurrentUser().UserID;
            var fromdate = string.IsNullOrEmpty(model.FromDate)
                ? DateTime.Now.Date
                : DateTime.ParseExact(model.FromDate, "dd/MM/yyyy", CultureInfo.InvariantCulture);
            var todate = string.IsNullOrEmpty(model.ToDate)
               ? DateTime.Now.Date.AddDays(1).AddSeconds(-1)
               : DateTime.ParseExact(model.ToDate, "dd/MM/yyyy", CultureInfo.InvariantCulture).AddDays(1).AddSeconds(-1);
            var channelIds = string.Empty;
            var channelAmounts = string.Empty;
            foreach (var channelInfo in channels
                .Where(c => !forms.Get(c.ChannelId + "_chkChannel").IsStringNullOrEmpty())
                .Where(c => forms.Get(c.ChannelId + "_txtChannelItems").ToInt32() > 0))
            {
                var amount = forms.Get(channelInfo.ChannelId + "_txtChannelItems").ToInt32();
                channelAmounts = channelAmounts.IsStringNullOrEmpty() ? amount.ToString() : "," + amount;
                channelIds = channelIds.IsStringNullOrEmpty() ? channelInfo.ChannelId.ToString() : "," + channelInfo.ChannelId;
            }
            if (maxRowPerPage.IsIntegerNull() || 
                channelIds.IsStringNullOrEmpty() || 
                channelAmounts.IsStringNullOrEmpty())
                return string.Empty;

            // Print
            var printId = ContactRepository.ContactPrintAll(branchId, fromdate, todate, channelIds, channelAmounts, maxRowPerPage, userId, DateTime.Now);
            return printId.ToString();
        }
      
        public ActionResult AcceptContactL1FromCollaborators()
        {
            ViewBag.PrintedPages = PrintForCollaboratorPageRepository.GetAll();
            var statusMaps = StoreData.ListStatusMap.Count > 0
                                     ? StoreData.ListStatusMap.Where(c => c.LevelId == (int)LevelType.L1).ToList()
                                     : StatusMapRepository.GetAllByLevelId((int)LevelType.L1);
            ViewBag.StatusMaps = statusMaps != null && statusMaps.Count > 0
                                     ? statusMaps.Where(c => c.StatusMapType == (int)StatusMapUsedBy.Distributor).ToList()
                                     : new List<StatusMapInfo>();
            return View();
        }
        [HttpPost]
        public JsonResult AcceptContactL1FromCollaborators(FormCollection form)
        {
            var internalDups = new HashSet<string>();
            var lstStatus = new List<AcceptL1StatusModel>();
            ViewBag.PrintedPages = PrintForCollaboratorPageRepository.GetAll();
            var statusMaps = StoreData.ListStatusMap.Count > 0
                                      ? StoreData.ListStatusMap.Where(c => c.LevelId == (int)LevelType.L1).ToList()
                                      : StatusMapRepository.GetAllByLevelId((int)LevelType.L1);
            ViewBag.StatusMaps = statusMaps != null && statusMaps.Count > 0
                                     ? statusMaps.Where(c => c.StatusMapType == (int)StatusMapUsedBy.Distributor).ToList()
                                     : new List<StatusMapInfo>();
            var contactCount = ConvertHelper.ToInt32(form.Get("txtContactCount"));
            for (var i = 1; i < contactCount + 1; i++)
            {
                var model = new AcceptL1StatusModel
                                {
                                    Status = 0,
                                    StatusText = "Nghiệm thu thành công",
                                    Mobile = form.Get(i + "_Mobile2") ?? string.Empty,
                                };

                // Check mobile
                if (!model.Mobile.IsStringNullOrEmpty())
                {
                    model.Mobile = Util.CleanAlphabetAndFirstZero(model.Mobile);
                    if (!Util.ValidateMobile(model.Mobile))
                    {
                        model.Status = 3;
                        model.StatusText = model.Mobile + " => Số điện thoại không đúng định dạng";
                        lstStatus.Add(model);
                        continue;
                    }
                    if (internalDups.Contains(model.Mobile))
                    {
                        model.Status = 3;
                        model.StatusText = model.Mobile + " => Số điện thoại bị trùng (trùng nội tại)";
                        lstStatus.Add(model);
                        continue;
                    }
                    internalDups.Add(model.Mobile);
                }

                var info = ContactRepository.GetInfo(ConvertHelper.ToInt32(form.Get(i + "_txtContactId")));
                if (info != null)
                {
                    if (info.StatusMapDistributorId.HasValue && info.StatusMapDistributorId.Value > 0)
                        continue;

                    model.Fullname = info.Fullname;
                    var statusMap = StoreData.ListStatusMap.FirstOrDefault(c => c.Id == ConvertHelper.ToInt32(form.Get(i + "_dropStatusMap")));
                    if (statusMap != null)
                    {
                        info.AcceptDateL1 = DateTime.Now;
                        info.StatusCareId = statusMap.StatusCareId;
                        info.StatusMapDistributorId = statusMap.Id;
                        ContactRepository.ContactsAcceptL1(info, UserContext.GetCurrentUser().UserID);

                        // Update phone
                        if (!string.IsNullOrEmpty(model.Mobile))
                        {
                             // Check redis
                            var duplicateId = CheckDuplicateProvider.Instance().IsDuplicate(model.Mobile, string.Empty, string.Empty, string.Empty, string.Empty);
                            if (duplicateId > 0 && duplicateId != info.Id)
                            {
                                var contactInfoDb = ContactRepository.GetInfo(duplicateId);
                                if (contactInfoDb == null) ViewBag.Message = "Cập nhật contact bị lỗi do trùng với contact khác trong hệ thống";
                                else
                                {
                                    var user = StoreData.ListUser.FirstOrDefault(c => c.UserID == contactInfoDb.UserId) ??
                                                   UserRepository.GetInfo(contactInfoDb.UserId);

                                    model.StatusText = user == null
                                                          ? "Sđt hoặc Email bạn nhập đã bị trùng với Ứng viên: " + contactInfoDb.Id + " - " + contactInfoDb.Fullname + " - Level " + contactInfoDb.LevelId + "- TVTS: chưa có ai chăm sóc"
                                                          : "Sđt hoặc Email bạn nhập đã bị trùng với Ứng viên: " + contactInfoDb.Id + " - " + contactInfoDb.Fullname + " - Level " + contactInfoDb.LevelId + "- TVTS: " + user.FullName;
                                }
                            }
                            else
                            {
                                try
                                {
                                    var phone = new PhoneInfo
                                    {
                                        IsPrimary = 0,
                                        ContactId = info.Id,
                                        PhoneType = ((int)PhoneType.MobilePhone).ToString(),
                                        PhoneNumber = ConvertHelper.ToString(form.Get(i + "_Mobile2")),
                                    };
                                    PhoneRepository.Create(phone);
                                    ContactRepository.UpdateAcceptance(info.Id, AcceptanceStatus.AcceptedL1, (int)StatusType.AcceptedL1FromCollaborator, info.StatusCareId, (int)LevelType.L1);
                                }
                                catch (Exception ex)
                                {
                                    model.Status = AcceptanceStatus.None;
                                    model.StatusText = "Có lỗi xảy ra: " + ex.Message;
                                }

                                // Redis
                                StoreData.LoadRedis(info.Id);
                            }
                        }
                        lstStatus.Add(model);
                    }
                }
                else
                {
                    model.Status = 5;
                    model.StatusText = "Không tồn tại";
                    lstStatus.Add(model);
                }
            }
            return new JsonResult { Data = lstStatus };
            //return View();
        }

        public ActionResult AcceptContactL2FromCollaborators()
        {
            return View();
        }
        [HttpPost]
        public JsonResult AcceptContactL2FromCollaborators(FormCollection form)
        {
            var internalDups = new HashSet<string>();
            var lstStatus = new List<AcceptL2StatusModel>();
            for (var i = 1; i <= 20; i++)
            {
                var model = new AcceptL2StatusModel
                                {
                                    Email = form.Get(i + "_Email") ?? string.Empty,
                                    Mobile = form.Get(i + "_Mobile") ?? string.Empty,
                                };
                model.Mobile = Util.CleanAlphabetAndFirstZero(model.Mobile);
                if (model.Mobile.IsStringNullOrEmpty()) continue;

                // Check mobile
                if (!model.Mobile.IsStringNullOrEmpty())
                {
                    if (!Util.ValidateMobile(model.Mobile))
                    {
                        model.Status = 3;
                        model.StatusText = model.Mobile + " => Số điện thoại không đúng định dạng";
                        lstStatus.Add(model);
                        continue;
                    }
                    if (internalDups.Contains(model.Mobile))
                    {
                        model.Status = 3;
                        model.StatusText = model.Mobile + " => Số điện thoại bị trùng (trùng nội tại)";
                        lstStatus.Add(model);
                        continue;
                    }
                    internalDups.Add(model.Mobile);
                }

                // Check email
                if (!model.Email.IsStringNullOrEmpty())
                {
                    if (!Util.ValidateEmail(model.Email))
                    {
                        model.Status = 2;
                        model.StatusText = model.Email + " => Email không đúng định dạng";
                        lstStatus.Add(model);
                        continue;
                    }
                    if (internalDups.Contains(model.Email))
                    {
                        model.Status = 2;
                        model.StatusText = model.Email + " => Email bị trùng (trùng nội tại)";
                        lstStatus.Add(model);
                        continue;
                    }
                    internalDups.Add(model.Email);
                }

                var info = ContactRepository.GetByMobile(model.Mobile);
                if (info != null)
                {
                    // Fullname
                    info.Fullname = form.Get(i + "_Fullname") ?? info.Fullname;
                    model.Fullname = info.Fullname;

                    if (info.LevelId < (int)LevelType.L2)
                    {
                        // Email
                        if (info.Email.IsStringNullOrEmpty())
                            info.Email = form.Get(i + "_Email") ?? info.Email;
                        else 
                            info.Email2 = form.Get(i + "_Email") ?? string.Empty;
                        model.Email = info.Email;

                        // Check redis
                        string outInfo;
                        var check = CheckDuplicateProvider.Instance().IsDuplicate(model.Mobile, string.Empty, string.Empty, info.Email, info.Email2, info.Id, out outInfo);
                        if (check)
                        {
                            model.Status = 4;
                            model.StatusText = "Trùng contact (thông tin trùng: " + outInfo + ")";
                            lstStatus.Add(model);
                            continue;
                        }

                        // Address
                        info.Address = form.Get(i + "_Location") ?? string.Empty;

                        // Location
                        var location = StoreData.ListLocation.FirstOrDefault(c => c.Name.ToLower() == form.Get(i + "_Location").ToLower());
                        info.LocationId = location != null ? location.LocationId : 1;

                        // EductionSchool
                        info.SchoolId = ConvertHelper.ToInt32(form.Get(i + "_SchoolId"));

                        // Major
                        string majorInfo;
                        var majorCode = form.Get(i + "_Major");
                        if (majorCode == "tc")
                        {
                            var majors = MajorRepository.GetAll() ?? new List<MajorInfo>();
                            majors.RemoveAll(c => c.MajorId == 1);

                            info.MajorId = majors.Count > 0 ? majors[majors.Count - 1].MajorId : 1;
                            majorInfo =
                                majors.Select(c => c.MajorId.ToString()).Aggregate(
                                    (total, curent) => total + "|" + curent);
                        }
                        else
                        {
                            var major = MajorRepository.GetByCode(majorCode);
                            info.MajorId = major != null ? major.MajorId : 1;
                            majorInfo = info.MajorId.ToString();
                        }

                        // CallDateDistributor
                        info.CallDateDistributor = form.Get(i + "_CallDate").ToDateTime() ?? DateTime.Now;

                        // StatusMapDistributorId
                        info.AcceptDateL2 = DateTime.Now;
                        info.StatusMapDistributorId = Constant.STATUSMAP_ACCEPT_L2;
                        if (info.AcceptDateL1 == null) info.AcceptDateL1 = info.AcceptDateL2;

                        // ContactLevelInfo
                        var contactLevel = ContactLevelInfoRepository.GetInfo(info.Id) ?? new ContactLevelInfo();
                        contactLevel.Majors = majorInfo;
                        contactLevel.MajorGrad = form.Get(i + "_MajorGrad");
                        contactLevel.EducationLevelNotes = form.Get(i + "_Notes");
                        contactLevel.SchoolGrad = form.Get(i + "_EducationSchool");
                        contactLevel.SchoolName = form.Get(i + "_EducationSchool");
                        contactLevel.HaveJob = form.Get(i + "_HaveJob").ToBoolean();
                        contactLevel.CollaboratorName = form.Get(i + "_Collaborator");
                        contactLevel.HaveLearnTransfer = form.Get(i + "_HaveLearnTransfer").ToBoolean();
                        contactLevel.CalledDate = form.Get(i + "_CallDate").ToDateTime() ?? DateTime.Now;
                        contactLevel.EducationLevels = ConvertHelper.ToString(form.Get(i + "_EducationLevelId"));

                        // Update
                        ContactRepository.Update(info);
                        ContactLevelInfoRepository.Update(contactLevel);
                        ContactRepository.UpdateAcceptance(info.Id, AcceptanceStatus.AcceptedL2,
                                                           (int) StatusType.AcceptedL2FromCollaborator,
                                                           info.StatusCareId, (int) LevelType.L2);

                        model.Status = 0;
                        model.StatusText = "Nghiệm thu thành công";
                        lstStatus.Add(model);

                        // Redis
                        StoreData.LoadRedis(info.Id);
                    }
                    else
                    {
                        model.Status = 6;
                        model.StatusText = model.Fullname + " => Contact này đã đc nghiệm thu rồi";
                        lstStatus.Add(model);
                    }
                }
                else
                {
                    model.Status = 5;
                    model.StatusText = model.Mobile + " => Số điện thoại không tồn tại";
                    lstStatus.Add(model);
                }
            }
            return new JsonResult { Data = lstStatus };
        }

        public ActionResult FilterContactReuse()
        {
            return View();
        }
        public ActionResult FilterContactToday()
        {
            int totalExists;
            int handoverCount;
            int completeInCount;
            int completeOutCount;
            int notCompleteCount;

            var branch = UserContext.GetDefaultBranch();
            var userId = UserContext.GetCurrentUser().UserID;
            ContactRepository.ContactsFilterStatictsToday(userId, branch, DateTime.Now, out handoverCount, out completeInCount, out completeOutCount, out notCompleteCount);
            ContactRepository.FilterTodayAll(userId, DateTime.Now.AddMonths(-1).AddDays(-1).Date, DateTime.Now.Date.AddSeconds(-1), branch, 1, 1, out totalExists);
            ViewBag.HandoverCount = handoverCount;
            ViewBag.CompleteInCount = completeInCount;
            ViewBag.CompleteOutCount = completeOutCount;
            ViewBag.NotCompleteCount = notCompleteCount;
            ViewBag.TotalExists = totalExists;
            return View();
        }
        public ActionResult FilterContactSearch()
        {
            return View();
        }
        public ActionResult FilterContactRecovery()
        {
            int totalRecords;
            var listUsers = StoreData.ListUser;
            var listConsultantNomrs = ConsultantNomrsRepository.GetAllByBranchId(UserContext.GetDefaultBranch(), 1, 1000, out totalRecords) ?? new List<ConsultantNomrsInfo>();
            foreach (var item in listConsultantNomrs)
            {
                var user = StoreData.ListUser.FirstOrDefault(c => c.UserID == item.ConsultantId);
                if (user == null) continue;

                item.GroupId = user.GroupId;
                item.GroupName = user.GroupName;
                if (!item.GroupName.IsStringNullOrEmpty()) continue;

                var group = StoreData.ListGroup.FirstOrDefault(c => c.GroupId == user.GroupId);
                if (group == null) continue;

                user.GroupName = group.Name;
                item.GroupName = group.Name;
            }
            listConsultantNomrs = listConsultantNomrs.Where(c => !c.GroupId.IsIntegerNull()).ToList();
            ViewBag.UserTvts = listUsers.Where(c => listConsultantNomrs.Exists(p => p.ConsultantId == c.UserID)).ToList();
            ViewBag.StatusMaps = StoreData.ListStatusMap.Count > 0
                                     ? StoreData.ListStatusMap
                                     : StatusMapRepository.GetAll();
            return View();
        }
        public ActionResult FilterContactHandover()
        {
            return View();
        }
        public ActionResult FilterContactCCL2Plus()
        {
            var branchId = UserContext.GetDefaultBranch();
            var userId = UserContext.GetCurrentUser().UserID;
            var levels = LevelRepository.GetAllWithContactCount(userId, branchId) ?? new List<LevelInfo>();
            foreach (var level in StoreData.ListLevel.Where(c => !levels.Exists(p => p.LevelId == c.LevelId)))
                levels.Add(level);
            ViewBag.LevelWithContactCount = levels.OrderBy(c => c.LevelId).ToList();
            return View();
        }
        public ActionResult FilterContactRecovered()
        {
            var listStatusCare = StoreData.ListStatusCare.Count > 0
                                    ? StoreData.ListStatusCare
                                    : StatusCareRepository.GetAll();
            const int total = 2;
            var array = new List<List<StatusCareInfo>>();
            for (var i = 0; i < total; i++)
            {
                var divice = (int)Math.Ceiling((double)listStatusCare.Count / (total - i));
                array.Add(listStatusCare.Take(divice).ToList());
                listStatusCare.RemoveRange(0, divice);
            }
            ViewBag.ArrayStatusCare = array;
            return View();
        }
        public ActionResult FilterContactSearchFast()
        {
            return View();
        }
        public ActionResult FilterContactForImporter()
        {
            var statusConnectTypes = new Dictionary<int, string>();
            foreach (var item in Enum.GetValues(typeof(StatusConnectType)))
                statusConnectTypes.Add((int)item, ObjectExtensions.GetEnumDescription((StatusConnectType)item));
            ViewBag.StatusConnectTypes = statusConnectTypes.Select(c => new { Id = c.Key, Name = c.Value });

            var importExcels = ImportExcelRepository.GetAll(1000);
            foreach (var item in importExcels) item.FilePath = (new FileInfo(item.FilePath)).Name;
            ViewBag.ImportExcels = importExcels;
            return View();
        }
        public ActionResult FilterContactAppointment()
        {
            var appointmentCallTypes = new Dictionary<int, string>();
            foreach (var item in Enum.GetValues(typeof(AppointmentCallType)))
                appointmentCallTypes.Add((int)item, ObjectExtensions.GetEnumDescription((AppointmentCallType)item));
            ViewBag.AppointmentCallTypes = appointmentCallTypes.Select(c => new { Id = c.Key, Name = c.Value });

            var list = new[]
            { 
                new { Id = 1, Name = "Campain 1" },
                new { Id = 2, Name = "Campain 2" } 
            }.ToList();
            ViewBag.Campains = list;
            return View();
        }
        public ActionResult FilterContactSearchManager()
        {
            int totalRecords;
            var listConsultantNomrs = ConsultantNomrsRepository.GetAllByBranchId(UserContext.GetDefaultBranch(), 1, 1000, out totalRecords);
            if (!listConsultantNomrs.IsNullOrEmpty())
            {
                foreach (var item in listConsultantNomrs)
                {
                    var user = StoreData.ListUser.FirstOrDefault(c => c.UserID == item.ConsultantId);
                    if (user != null && user.GroupName.IsStringNullOrEmpty())
                    {
                        var group = StoreData.ListGroup.FirstOrDefault(c => c.GroupId == user.GroupId);
                        if (group != null) user.GroupName = group.Name;
                    }
                    item.FullName = user == null
                                        ? string.Empty
                                        : (user.GroupName.IsStringNullOrEmpty()
                                               ? user.FullName
                                               : user.GroupName + " - " + user.FullName);
                }
            }
            ViewBag.ConsultantNomrs = listConsultantNomrs;
            return View();
        }
        public ActionResult FilterContactSearchAdvance()
        {
            var branchId = UserContext.GetDefaultBranch();
            var userId = UserContext.GetCurrentUser().UserID;
            var levels = LevelRepository.GetAllWithContactCount(userId, branchId) ?? new List<LevelInfo>();
            foreach (var level in StoreData.ListLevel.Where(c => !levels.Exists(p => p.LevelId == c.LevelId)))
                levels.Add(level);
            ViewBag.LevelWithContactCount = levels.OrderBy(c => c.LevelId).ToList();
            return View();
        }
        public ActionResult FilterContactDuplicateImport()
        {
            return View();
        }
        public ActionResult FilterContactSearchForFilter()
        {
            return View();
        }
        public ActionResult FilterContactDuplicateConsultant()
        {
            return View();
        }
        public ActionResult FilterContactDuplicateDistributor()
        {
            return View();
        }
       
        [NotAuthorizeAttribute]
        public JsonResult GetForFilterTeam(int branchId, int collectorId, int channelId, int importId, int levelId, int sourceTypeId, int schoolId, int statusId, int page, int rows)
        {
            var list = new MyContactListModel();
            var lstModel = new List<ContactModel>();
            int totalRecords;
            var data = ContactRepository.GetForFilterTeam(branchId, collectorId, channelId, importId, levelId, sourceTypeId, schoolId, statusId, page, rows, out totalRecords);
            foreach (var info in data)
            {
                var objModel = ObjectHelper.Transform<ContactModel, ContactInfo>(info);
                var ctStatus = StatusRepository.GetInfo(info.StatusId);
                if (ctStatus != null)
                {
                    objModel.StatusName = ctStatus.Name;
                }
                var contactLevel = ContactLevelInfoRepository.GetInfo(info.Id);
                if (contactLevel != null)
                {
                    objModel.CollaboratorName = contactLevel.CollaboratorName;
                    objModel.SchoolGrad = contactLevel.SchoolGrad;
                    objModel.MajorGrad = contactLevel.MajorGrad;
                    objModel.HaveJob = contactLevel.HaveJob;
                    objModel.Notes = contactLevel.EducationLevelNotes;
                }
                var collector = CollectorRepository.GetInfo(info.CollectorId);
                var channel = ChannelRepository.GetInfo(info.ChannelId);
                var phones = PhoneRepository.GetByContact(info.Id);
                foreach (var phone in phones)
                {
                    if (phone.IsPrimary == 1)
                    {
                        objModel.Mobile = phone.PhoneNumber;
                    }
                    else if (phone.PhoneType == PhoneType.HomePhone.ToString())
                    {
                        objModel.Tel = phone.PhoneNumber;
                    }
                    else
                    {
                        objModel.Mobile2 = phone.PhoneNumber;
                    }

                }
                if (collector != null) objModel.CollectorName = collector.Name;
                if (channel != null) objModel.ChannelName = channel.Name;

                lstModel.Add(objModel);
            }
            list.UserData = totalRecords;
            list.Rows = lstModel;
            list.Page = page;
            list.Total = (totalRecords / rows) + 1;
            list.Records = rows;
            return new JsonResult { Data = list, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
        }
        public int CountByChannel(int branchId, int sourceTypeId, int levelId, int channelId, string from, string to)
        {
            try
            {
                var dtFrom = string.IsNullOrEmpty(from)
                                 ? DateTime.Now.Date
                                 : DateTime.ParseExact(from, "dd/MM/yyyy", CultureInfo.InstalledUICulture);
                var dtTo = string.IsNullOrEmpty(from)
                                 ? DateTime.Now.AddDays(1).Date
                                 : DateTime.ParseExact(to, "dd/MM/yyyy", CultureInfo.InstalledUICulture);
                return ContactRepository.CountByChannel(branchId, sourceTypeId, levelId, channelId, dtFrom, dtTo);
            }
            catch
            {
                return 0;
            }
        }
        public JsonResult BuilGridAcceptL2()
        {
            var objListModel = new AcceptL2ContactListModel();
            var data = new List<AcceptL2ContactModel>();
            for (var i = 0; i < 10; i++)
            {
                var objModel = new AcceptL2ContactModel();
                data.Add(objModel);
            }
            objListModel.Rows = data;
            objListModel.Page = 1;
            objListModel.Total = 1;
            objListModel.Records = 10;
            return new JsonResult { Data = objListModel, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
        }
    }
}
